<?php
/**
 *
 *   User:King
 *   Date:2021/12/22 13:39
 */

namespace app\bank_api\library;


use fast\Http;
use think\Env;

class Sms
{
    /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 300;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;

    public static function send($mobile,$event = 'default'){
        $app_key = Env::get('sms.app_key') ?? '';
        $app_code = Env::get('sms.app_code') ?? '';
        $apps_ecret = Env::get('sms.app_secret') ?? '';
        $gateway = Env::get('sms.gateway') ?? '';

//        $sms = \app\common\model\Sms::where(['mobile' => $mobile,'event' => $event])->order('id DESC')->find();
//        if(!empty($sms)){
//            $expires_time = $sms->createtime + self::$expire;//过期时间
//            if($expires_time > time()){
//                return [false,'短信正在发送，请稍后再试'];
//            }
//        }

        $code = mt_rand(100000,999999);
        $tiemstamp = self::getMillisecond();
        $data = [
            'appkey' => $app_key,
            'appcode'=> $app_code,
            'sign'   => md5($app_key.$apps_ecret.$tiemstamp),
            'phone'  => $mobile,
            'msg'    =>'【积分系统】验证码为：'.$code.',有效期为5分钟。',
            'timestamp'=>$tiemstamp,
        ];
        $res = Http::post($gateway,json_encode($data),[],['Content-Type: application/json']);

        $result = json_decode($res,true);
        if($result['code'] != '00000'){
            return [false,'发送失败'];
        }
        $send_res = \app\common\model\Sms::create(['event' => $event,'code'=> $code,'mobile' => $mobile],true);
        if(!$send_res){
            return [false,'发送失败'];
        }
        return [true,'发送成功'];
    }

    public static function check($mobile, $code, $event = 'default'){
        $sms = \app\common\model\Sms::where(['mobile' => $mobile,'code' => $code,'event' => $event])->order('id DESC')->find();
        if(empty($sms)){
            return [false,'验证码错误'];
        }
        $expires_time = $sms->createtime + self::$expire;//过期时间
        if($expires_time < time()){
            return [false,'验证码过期'];
        }
        $res = \app\common\model\Sms::where('mobile', $mobile)->delete();
        if(!$res){
            return [false,'验证失败'];
        }
        return [true,'验证成功'];
    }

    public static function getMillisecond(){
        list($msec, $sec) = explode(' ', microtime());

        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

        return $msectimes = substr($msectime,0,13);

    }
}